/*
 * @Author: 9ilk 3535851673@qq.com
 * @Date: 2024-11-27 20:15:18
 * @LastEditors: 9ilk 3535851673@qq.com
 * @LastEditTime: 2024-11-27 20:15:45
 * @FilePath: /zhuang/Cond/Mutex.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include <iostream>
#include <pthread.h>


namespace MutexModule
{
    class Mutex
    {
    public:
    //互斥锁不允许拷贝 要求多线程使用同一把锁
        Mutex(const Mutex&) = delete;
        const Mutex& operator= (const Mutex&) = delete;
        Mutex()
        {
          int n = ::pthread_mutex_init(&_lock,nullptr);
          (void)n;
        }
        ~Mutex()
        {
            int n = ::pthread_mutex_destroy(&_lock);
            (void)n;
        }
        void Lock()
        {
            int n = ::pthread_mutex_lock(&_lock);
            (void)n;
        }
        void Unlock()
        {
            int n = ::pthread_mutex_unlock(&_lock);
            (void)n;
        }
        pthread_mutex_t* LockPtr()
        {
             return &_lock;
        }

    private:
       pthread_mutex_t _lock;
    };

    class LockGuard
    {
      public:
         LockGuard(Mutex& mtx)
         :_mtx(mtx)
         {
            _mtx.Lock();
         }

         ~LockGuard()
         {
            _mtx.Unlock();
         } 
      private:
       Mutex& _mtx; //不能拷贝 所以引用   
    };

}
